package dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import util.UtilMD5;

import biz.dao.UserDao;
import biz.domain.User;

@Repository
public class HibernateUserDao implements UserDao {

	@Autowired
	private HibernateTemplate hibernateTemplate;
	private final static String findHQL = "from User";
	private final static String findHQLbyUser = "from User where name = ? and pass = ?";

	@SuppressWarnings("unchecked")
	public List<User> findUser() {
		return hibernateTemplate.find(findHQL);
	}
	
	@SuppressWarnings("unchecked")
	public boolean findUser(User user) {
		boolean isUser = false;
		this.setMD5Pass(user);
		Object values[] = {user.getName(),user.getPass()};
		List<User> result = hibernateTemplate.find(findHQLbyUser,values);
		if(result.size()>0){
			isUser = true;
		}
		return isUser;
	}
	
	public void addUser(User user) {
		this.setMD5Pass(user);
		hibernateTemplate.save(user);
		hibernateTemplate.flush();
	}

	public void removeUser(User user) {
		hibernateTemplate.delete(user);
		hibernateTemplate.flush();
	}

	public void updateUser(User user) {
		hibernateTemplate.update(user);
		hibernateTemplate.flush();
	}

	private void setMD5Pass(User user){
		try {
			String pass = user.getPass();
			pass = UtilMD5.encodePassdigiest(pass);
			user.setPass(pass);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return;
	}
	
}
